﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using System.Threading;
using System.Windows;
using System.Windows.Threading;
using BLL;
using Client.QuizService;
using Client.View;

namespace Client.ViewModel
{
    class SelectQuizViewModel : BaseViewModel
    {
        #region Bound properties

        private ObservableCollection<Quiz> quizList;

        public ObservableCollection<Quiz> QuizList
        {
            get
            {
                if (quizList == null)
                {
                    quizList = new ObservableCollection<Quiz>();
                }
                return quizList;
            }
        }

        #endregion

        #region Commands

        private AsyncDelegateCommand listQuizesCommand;
        public AsyncDelegateCommand ListQuizesCommand
        {
            get {
                if (listQuizesCommand == null)
                    listQuizesCommand = new AsyncDelegateCommand(ListQuizes);
                return listQuizesCommand; 
            }
        }

        #endregion 

        #region Command methods

        protected void ListQuizes(object parameter)
        {
            int difficulty;
            if (Int32.TryParse(parameter.ToString(), out difficulty))
            {
                try
                {
                    using (var srv = new QuizServiceClient())
                    {
                        srv.GetQuizesByDifficultyCompleted += srv_GetQuizesByDifficultyCompleted;
                        srv.GetQuizesByDifficultyAsync(difficulty);
                    }
                }
                catch
                {
                    MessageBox.Show("Hát ez nem sikerült, bocsi.");
                }
            }
        }

        #endregion

        void srv_GetQuizesByDifficultyCompleted(object sender, GetQuizesByDifficultyCompletedEventArgs e)
        {
            var list = e.Result;

            Dispatcher.BeginInvoke((Action) delegate
            {
                QuizList.Clear();

                if (list == null) return;
                
                foreach (var item in list)
                {
                    QuizList.Add(item);
                }
            });
        }
    }
}